package com.bianhua.controller;

import com.bianhua.entity.User;
import com.bianhua.framework.role.RequiresRoles;
import com.bianhua.framework.role.Role;
import com.bianhua.service.UserService;
import com.bianhua.utils.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("create")
    @RequiresRoles(type = Role.ADMIN)
    public Result create(@RequestBody User user){
        int flag = userService.create(user);
        if(flag>0){
            return Result.ok();
        }else{
            return Result.fail();
        }
    }

    @GetMapping("delete")
    public Result delete(String ids){
        int flag = userService.delete(ids);
        if(flag>0){
            return Result.ok();
        }else{
            return Result.fail();
        }
    }

    @PostMapping("update")
    public Result update(@RequestBody User user){
        int flag = userService.update(user);
        if(flag>0){
            return Result.ok();
        }else{
            return Result.fail();
        }
    }

    @PostMapping("pwd")
    public Result updatePwd(@RequestBody Map<String,String> map){
        Integer id = Integer.parseInt(map.get("id"));
        //原密码
        String  spassword = map.get("spassword");
        //新密码
        String  npassword = map.get("npassword");
        User detail = userService.detail(id);
        if(!spassword.equals(detail.getPassword())){
            return Result.fail("原密码错误");
        }
        User user = new User();
        user.setId(id);
        user.setPassword(npassword);
        int flag = userService.updateSelective(user);
        if(flag>0){
            return Result.ok();
        }else{
            return Result.fail();
        }
    }

    @GetMapping("detail")
    public Result detail(Integer id){
        return  Result.ok(userService.detail(id));
    }

    @PostMapping("query")
    @RequiresRoles(type = Role.ADMIN)
    public Map<String,Object> query(@RequestBody  User user){
        PageInfo<User> pageInfo = userService.query(user);
        return Result.ok(pageInfo);
    }

}
